package faac.modules.chat;

import java.util.HashMap;
import faac.modules.ab.Cmd;
import faac.modules.ab.CommandParser;
import faac.protocol.IcqProtocol;
import faac.util.Log;

@SuppressWarnings("unchecked")
public class Filter {
    public ChatServer srv;
    private int order  = 0;
    private HashMap<String, Cmd> commands = new HashMap<String, Cmd>();
    private CommandParser parser;
    private ChatCommandProc cmd;
    private HashMap<String, FilterInfoMap> FilterInfoMap;
    private String CMD = "";
    private String object = "";
    private long TIME = 5*60000;

    public Filter(ChatCommandProc c){
        parser = new CommandParser(commands);
        cmd = c;
        FilterInfoMap = new HashMap<String, FilterInfoMap>();
        init();
    }

public class FilterInfoMap {
        private String uin;
        private long vremia;
        private String msg;
        private String cmd;

        public FilterInfoMap(String _uin, String _cmd, String _msg, long expire) {
            vremia = System.currentTimeMillis() + expire;
            uin = _uin;
            cmd = _cmd;
            msg = _msg;
        }

        public String getMsg(){return msg;}
        public String getUin() {return uin;}
        public String getCmd() {return cmd;}
        public boolean isExpire() {return System.currentTimeMillis()>vremia;}
    }

    private void init() {
        commands.put("!act", new Cmd("!act","",1));
    }

    public boolean Parse(IcqProtocol proc, String uin, String mmsg) {
        String tmsg = mmsg.trim();
        int tp = 0;
        if(FilterInfoMap.containsKey(uin))
        if(!FilterInfoMap.get(uin).isExpire())
        tp = parser.parseCommand(FilterInfoMap.get(uin).getCmd());
        else {
            tp = parser.parseCommand(tmsg);
            order = 0;
            CMD = "";
            FilterInfoMap.remove(uin);
        }else
        tp = parser.parseCommand(tmsg);
        int tst=0;
        if(tp<0)
        tst=0;
        else
        tst = tp;
        boolean f = true;
        switch (tst){
            case 1:
                Action(proc, uin, mmsg);
            break;
            default:
            f = false;
        }
        return f;
    }

    private void Action(IcqProtocol proc, String uin, String mmsg){
        if(!cmd.isAdmin(proc, uin)) return;
        if (object.equals("")){
            proc.mq.add(uin,"Реклама не обнаружена");
            return;
        }
        try{
            if(order == 0){
                ActionNum(proc, uin, mmsg);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            proc.mq.add(uin,"При выполнении возникла ошибка");
            order = 0;
            CMD = "";
        }
    }

    private void ActionNum(IcqProtocol proc, String uin, String mmsg){
        String r = "Реклама"; //Получаем причину
        int msg  = 0;
        boolean FLT = false;
        if(FilterInfoMap.containsKey(uin)){
            try{
                if (mmsg.equals("")) return;
                msg = Integer.parseInt(mmsg);
            } catch(NumberFormatException e){
                proc.mq.add(uin,"Сделайте Ваш выбор:\n" +
                        "0 - Пропустить\n" +
                        "1 - Кик\n" +
                        "2 - Бан");
                return;
            }
            if (msg < 0 || msg > 2) {
                proc.mq.add(uin,"Выбор должен быть:\n" +
                        "0 - Пропустить\n" +
                        "1 - Кик\n" +
                        "2 - Бан");
                return;
            }
            FLT = true;
            FilterInfoMap.remove(uin);
        }
        if(!FLT){
            CMD = mmsg;
            FilterInfoMap.put(uin, new FilterInfoMap(uin, CMD, mmsg, TIME));
            return;
        }
        if (msg == 0){
            proc.mq.add(uin,"Действие отменено");
            object = "";
            order = 0;
            CMD = "";
        }
        if (msg == 1){
            cmd.tkick(proc, object, cmd.psp.getIntProperty("chat.maxKickTime"), cmd.srv.us.getUser(uin).id, r);
            proc.mq.add(uin,"Пользователь кикнут на " + cmd.psp.getIntProperty("chat.maxKickTime") + " мин.");
            object = "";
            order = 0;
            CMD = "";
        }
        if (msg == 2){
            cmd.ban(proc, object, uin, r);
            proc.mq.add(uin,"Пользователь забанен");
            object = "";
            order = 0;
            CMD = "";
        }
    }

    public String mmsg (IcqProtocol proc, String mmsg, String uin){ //Фильтр рекламы
        String msg = mmsg;
        int a=0;
        if (cmd.psp.getBooleanProperty("filter.mat.on")){
            if (testMat(msg)){
                msg = cmd.psp.getStringProperty("filter.change.mat");
            }
        }
        Users uss = cmd.srv.us.getUser(uin);
        String[] antirazd= {".",";",":","*","(",")","!","@","#","%"," ","'","-","_","?","$","^","=","+","<",">"};
        String[] antiuin = cmd.psp.getStringProperty("filter.antiuin").split(";");
        String anticaps = mmsg.toLowerCase();
        if(mmsg.indexOf("Автоматическое сообщение")>=0 && cmd.psp.getBooleanProperty("filter.automsg.on")){
            mmsg="";
            msg = mmsg;
            return msg;
        }
        for(int i=0;i<antirazd.length;i++){
            anticaps = anticaps.replace(antirazd[i],"");
        }
        for(int i=0;i<antiuin.length;i++){
            anticaps = anticaps.replace(antiuin[i],"0");
        }
        char[] c = anticaps.toCharArray();
        for (int i = 0; i < c.length; i++){
            if(c[i]==48)a++;//=="0"
            if(a > cmd.psp.getIntProperty("filter.num")){
                if(!mmsg.substring(0, 1).equals("!") && !mmsg.substring(0, 1).equals("+") && uss.state == UserWork.STATE_CHAT){
                    Log.getLogger(srv.getName()).talk("фильтр рекламы: " + mmsg);
                    if (cmd.psp.getBooleanProperty("filter.adm")){
                        String s = cmd.psp.getStringProperty("bot.adminUIN");
                            cmd.srv.getIcqProcess(cmd.srv.us.getUser(s).basesn).mq.add(s, "-=[Фильтр рекламы]=-:\n" +
                                    "---------------\n" +
                                    "UIN: " + uin + "\n" +
                                    "Ник: " + "[" + uss.id + "]" + " - " + uss.localnick + "\n" +
                                    "---------------\n" +
                                    "Cообщение: " + mmsg + "\n" +
                                    "---------------\n" +
                                    "Действие на ваш выбор:\n" +
                                    "0) Пропустить\n" +
                                    "1) !кик " + uss.id + " " + cmd.psp.getIntProperty("chat.maxKickTime") + " реклама\n" +
                                    "2) !бан " + uss.id + " реклама");
                        object = uin;
                        Parse(proc, s, "!act");
                    }
                    if (cmd.psp.getBooleanProperty("filter.replace")) {
                        mmsg = cmd.psp.getStringProperty("filter.change");
                    }
                    msg = mmsg;
                    return msg;
                }
            }
        } return msg;
    }

    private boolean testMat(String msg){
        String[] s = msg.trim().split(" ");
        for(int i=0;i<s.length;i++){
            if(!test(s[i], ChatProps.getInstance(cmd.srv.getName()).getStringProperty("adm.noMatString").split(";"))){
                if(test(s[i], ChatProps.getInstance(cmd.srv.getName()).getStringProperty("adm.matString").split(";")))
                return true;
            }
        }
        return false;
    }

    private boolean test(String msg, String[] testStr){
        for(int i=0;i<testStr.length;i++) {
            if(msg.toLowerCase().indexOf(testStr[i])>=0) return true;
        }
        return false;
    }
}